#include "Server.h"

static int getCount = 0;
static int postCount = 0;

Server::Server(QWidget *parent)
    : QWidget(parent)
{
    ui.setupUi(this);

    m_updateTimer = new QTimer(this);
    connect(m_updateTimer, &QTimer::timeout, this, &Server::updateClientTable);
    m_updateTimer->start(1000);

    initHttp();
    initTable();


    initTCPServer();
}

Server::~Server()
{
    if (m_updateTimer) {
        if (m_updateTimer->isActive()) m_updateTimer->stop();
        m_updateTimer->deleteLater();
    }
    stopServer();

}

void Server::initHttp()
{
    m_httpServer = QSharedPointer<QNetworkHttpServer>::create(this);

    m_httpServer->postJsonApi("/api/postA", [&](const SimpleRequest& req, SimpleResponse& res) {
        ui.label_reciveMsg->clear();
        ui.label_reciveMsg->setText(QString::fromStdString(req.body));

        QString clientName;
        QString uidStr;
        QJsonParseError error;
        const QJsonDocument& document = QJsonDocument::fromJson(req.body.c_str(), &error);
        if (QJsonParseError::NoError == error.error) {
            const QJsonObject& programmerObject = document.object();
            QString str1 = programmerObject.value("str1").toString();
            QString str2 = programmerObject.value("str2").toString();
            clientName = programmerObject.value("client_name").toString();
            uidStr = programmerObject.value("uid").toString();

            ui.label_str1->clear();
            ui.label_str2->clear();
            ui.label_str1->setText(str1);
            ui.label_str2->setText(str2);
        }

        // 更新/创建客户端信息
        if (!m_clientInfos.contains(uidStr)) {
            ClientInfo info;
            info.name = clientName;
            info.address = QString::fromStdString(req.remote_addr);
            info.port = req.remote_port;
            info.postCount = 0;
            info.getCount = 0;
            m_clientInfos[uidStr] = info;
        }
        // 更新统计信息
        m_clientInfos[uidStr].postCount++;
        m_clientInfos[uidStr].lastActive = QDateTime::currentMSecsSinceEpoch();

        res.status = HttpStatusCode::OK_200;
        QJsonObject json;
        json["str"] = "post success!!!";
        json["count"] = postCount++;

        res.body = QJsonDocument(json).toJson(QJsonDocument::Compact).toStdString();
        });

    m_httpServer->listen(8080);
}

void Server::initTable()
{
    QStringList headerList;
    headerList << "客户端名称" << "ip地址" << "端口" << "post请求" << "最后活跃时间";

    ui.tableWidget_info->setColumnCount(headerList.size());
    ui.tableWidget_info->setHorizontalHeaderLabels(headerList);
    ui.tableWidget_info->setSelectionBehavior(QAbstractItemView::SelectRows);
    ui.tableWidget_info->setEditTriggers(QAbstractItemView::NoEditTriggers);
    ui.tableWidget_info->horizontalHeader()->setSectionResizeMode(QHeaderView::Interactive);
}

void Server::updateClientTable() {
    ui.tableWidget_info->setRowCount(m_clientInfos.size());
    QList<QString> clientsToRemove;

    int row = 0;
    for (auto it = m_clientInfos.begin(); it != m_clientInfos.end(); ++it, ++row) {
        const ClientInfo& info = it.value();

        // 设置表格项
        QTableWidgetItem* nameItem = new QTableWidgetItem(info.name);
        nameItem->setTextAlignment(Qt::AlignCenter);  // 水平垂直居中
        QTableWidgetItem* addrItem = new QTableWidgetItem(info.address);
        addrItem->setTextAlignment(Qt::AlignCenter);
        QTableWidgetItem* portItem = new QTableWidgetItem(QString::number(info.port));
        portItem->setTextAlignment(Qt::AlignCenter);
        QTableWidgetItem* postCountItem = new QTableWidgetItem(QString::number(info.postCount));
        postCountItem->setTextAlignment(Qt::AlignCenter);

        ui.tableWidget_info->setItem(row, 0, nameItem);
        ui.tableWidget_info->setItem(row, 1, addrItem);
        ui.tableWidget_info->setItem(row, 2, portItem);
        ui.tableWidget_info->setItem(row, 3, postCountItem);

        // 计算最后活跃时间（秒）
        qint64 inactiveSec = (QDateTime::currentMSecsSinceEpoch() - info.lastActive) / 1000;
        if (inactiveSec > 600) { // 
            clientsToRemove.append(it.key());
            continue; 
        }
        QString timeText;
        if (inactiveSec > 60) { 
            timeText = QString("%1分钟前").arg(inactiveSec / 60);
        }
        else {
            timeText = QString("%1秒前").arg(inactiveSec);
        }
        ui.tableWidget_info->setItem(row, 4, new QTableWidgetItem(timeText));

        QColor bgColor;
        if (inactiveSec > 300) { // 5分钟
            bgColor = QColor(255, 150, 150); // 浅红色
        }
        else if (inactiveSec > 60) { // 1分钟
            bgColor = QColor(255, 255, 150); // 浅黄色
        }
        else {
            bgColor = QColor(150, 255, 150); // 浅绿色
        }
        // 设置不同颜色表示活跃状态
        for (int col = 0; col < ui.tableWidget_info->columnCount(); ++col) {
            QTableWidgetItem* item = ui.tableWidget_info->item(row, col);
            item->setBackground(bgColor);
        }
    }

    // 移除超时客户端
    for (auto it : clientsToRemove) {
        if (m_clientInfos.contains(it)) {
            qDebug() << "移除超时客户端:" << m_clientInfos[it].name;
            m_clientInfos.remove(it);
        }
    }
    ui.tableWidget_info->setRowCount(m_clientInfos.size());
}





/// <summary>
/// TCP
/// </summary>
void Server::initTCPServer()
{
    connect(&m_server, &QTcpServer::newConnection, this, &Server::slot_newConnection);
    if (!m_server.listen(QHostAddress::Any, 8081)) {
        qDebug() << "TCP 启动失败";
    }
}
void Server::stopServer()
{
    if (m_server.isListening())
    {
        for (auto socket : m_clientSockets)
        {
            bool signal = socket->blockSignals(true);
            socket->close();
            socket->blockSignals(signal);
        }
    }

    m_clientSockets.clear();
    m_server.close();
}
void Server::slot_newConnection() {
    QTcpSocket* clientSocket = m_server.nextPendingConnection();
    if (clientSocket == nullptr)
        return;

    m_clientSockets.insert(clientSocket);

    connect(clientSocket, &QTcpSocket::readyRead, this, &Server::slot_reciveData);
    connect(clientSocket, &QTcpSocket::disconnected, this, &Server::slot_disconnected);
}
void Server::slot_disconnected() {
    QTcpSocket* socket = static_cast<QTcpSocket*>(sender());
    if (socket)
    {
        m_clientSockets.remove(socket);
        socket->deleteLater();
    }
}
void Server::slot_reciveData()
{
    QTcpSocket* socket = static_cast<QTcpSocket*>(sender());

    if (socket->bytesAvailable()) {
        QByteArray data = socket->readAll();
    }

    QByteArray data = "success";
    socket->write(data);

    //QByteArray protocolData = socket->readAll();
    //bool unpackSuccess = false;
    //QByteArray unpacked = CustomProtocol::unpackData(protocolData, unpackSuccess);

    //if (unpackSuccess) {
    //    QString text = QString::fromUtf8(unpacked);
    //    qDebug() << "Received text:" << text;
    //    ui.lineEdit_tcpRecive->setText(text);


    //    // 模拟写反馈
    //    QString data = "request success";
    //    QByteArray protocolData = CustomProtocol::packData(data.toUtf8());
    //    if (!socket || socket->state() != QAbstractSocket::ConnectedState) {
    //        qWarning() << "Socket is not connected";
    //        return;
    //    }
    //    socket->write(protocolData);
    //    socket->flush();
    //}
    //else {
    //    qDebug() << "Protocol unpack failed! Raw data:" << protocolData.toHex();
    //}
}